//
//  NRWCarInsuranceManagetVC.m
//  New_Runway
//
//  Created by 张记 on 2018/6/5.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarInsuranceManagetVC.h"
#import "NRWCarInsuranceOrderVC.h"

@interface NSURLRequest (InvalidSSLCertificate)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;

@end
@interface NRWCarInsuranceManagetVC ()<WKScriptMessageHandler>
@property (nonatomic, strong) NSURLRequest *request;
//判断是否是HTTPS的
@property (nonatomic, assign) BOOL isAuthed;
//返回按钮
@property (nonatomic, strong) UIButton *backItem;
//关闭按钮
@property (nonatomic, strong) UIButton *closeItem;
//下面的三个属性是添加进度条的
@property (nonatomic, assign) BOOL theBool;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation NRWCarInsuranceManagetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBarView.leftItem.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationBarView.rightItem setTitle:@"订单" forState:UIControlStateNormal];
    self.navigationBarView.titleLabel.text = self.mainTitle;
    self.wkwebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, self.navH, self.view.frame.size.width, self.view.frame.size.height - self.BotH - self.navH )];
    self.wkwebView.navigationDelegate = self;
    [self.view addSubview:self.wkwebView];
    [self addLeftButton];
    //添加进度条（如果没有需要，可以注释掉
    [self addProgressBar];
    NSURL *url = [NSURL URLWithString:self.htmlString];
    self.request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:5.0];
    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
    [self.wkwebView loadRequest:self.request];
    
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSURLRequest *urlstr = navigationAction.request;
    _currUrl = [urlstr.URL absoluteString];
    NSString* scheme = [[navigationAction.request URL] scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSURLRequest *urlstr = navigationAction.request;
        NSString *tel = [urlstr.URL absoluteString];
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"%@",tel];
        UIWebView *callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
        [self.view addSubview:callWebview];
    }
    
    if ([scheme isEqualToString:@"https"]) {
        if (!self.isAuthed) {
            NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:navigationAction.request delegate:self];
            [conn start];
            [webView stopLoading];
            //            decisionHandler(YES);
        }
    }
    decisionHandler(YES);
}

#pragma mark ================= NSURLConnectionDataDelegate <NSURLConnectionDelegate>

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0) {
        self.isAuthed = YES;
        //NSURLCredential 这个类是表示身份验证凭据不可变对象。凭证的实际类型声明的类的构造函数来确定。
        NSURLCredential *cre = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:cre forAuthenticationChallenge:challenge];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"网络不给力");
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.isAuthed = YES;
    //webview 重新加载请求。
    [self.wkwebView loadRequest:self.request];
    [connection cancel];
}

#pragma mark - 添加关闭按钮

- (void)addLeftButton
{
    [self.navigationBarView addSubview: self.backItem];
}

//点击返回的方法
- (void)backNative
{
    
    //判断是否有上一层H5页面
    if ([self.wkwebView canGoBack]) {
        //如果有则返回
        [self.wkwebView goBack];
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮
        [self.navigationBarView addSubview:self.closeItem];
    } else {
        [self closeNative];
    }
}

//关闭H5页面，直接回到原生页面
- (void)closeNative
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - init

- (UIButton *)backItem
{
    if (!_backItem) {
        _backItem = [[UIButton alloc] init];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *image = [UIImage imageNamed:@"nav_common_back_n"];
        [btn setImage:image forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:17]];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.frame = CGRectMake(2, self.navH-44, 40, 44);
        _backItem = btn;
    }
    return _backItem;
}

- (UIButton *)closeItem
{
    if (!_closeItem) {
        
        _closeItem = [[UIButton alloc] init];
        [_closeItem addTarget:self action:@selector(closeNative) forControlEvents:UIControlEventTouchUpInside];
        [_closeItem setTitle:@"关闭" forState:UIControlStateNormal];
        [_closeItem setTitleColor:kColorWhite() forState:UIControlStateNormal];
        [_closeItem setFrame:CGRectMake(45, self.navH - 44, 40, 44)];
        
        
    }
    return _closeItem;
}

#pragma mark - 下面所有的方法是添加进度条

- (void)addProgressBar
{
    // 仿微信进度条
    CGFloat progressBarHeight = 0.5f;
    //    CGRect navigationBarBounds = self.navigationBarView.bounds;
    CGRect barFrame = CGRectMake(0, self.navH, Screen_width, progressBarHeight);
    self.progressView = [[UIProgressView alloc] initWithFrame:barFrame];
    self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    self.progressView.trackTintColor = MAIN_NAV_COLOR(); //背景色
    self.progressView.progressTintColor = kColorWhite(); //进度色
    [self.view addSubview:self.progressView];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //移除progressView  because UINavigationBar is shared with other ViewControllers
    [self.progressView removeFromSuperview];
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    self.progressView.progress = 0;
    self.theBool = false;
    //0.01667 is roughly 1/60, so it will update at 60 FPS
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01667 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];
}
//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    self.theBool = true; //加载完毕后，进度条完成
    //执行Js
    kSelfWeak;
    NSString *inputValueJS = @"document.title";
    //执行Js
    [webView evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
        weakSelf.navigationBarView.titleLabel.text = response;
    }];
}


- (void)timerCallback
{
    if (self.theBool) {
        if (self.progressView.progress >= 1) {
            self.progressView.hidden = true;
            [self.timer invalidate];
        } else {
            self.progressView.progress += 0.1;
        }
    } else {
        self.progressView.progress += 0.1;
        if (self.progressView.progress >= 0.9) {
            self.progressView.progress = 0.9;
        }
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    
   
}
-(void)rightItemClick{
    NRWCarInsuranceOrderVC *orderVC = [[NRWCarInsuranceOrderVC alloc] init];
    NSString *url = [NSString stringWithFormat:@"https://h5.ztwltech.com/zkyq-web/orderShow/orderPage?agentCode=GLZqjc3oId9Usoyh&accountNo=%@",[NRWCarUser sharedUser].userId];
    orderVC.mainTitle = @"订单";
    orderVC.htmlString = url;
    [self.navigationController pushViewController:orderVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
